from django.contrib import admin
from django.forms import ValidationError
from django.utils.translation import ugettext_lazy as _
from djwheel.adminutils import create_advanced_admin_form
from treemenus.admin import Menu, MenuAdmin, MenuItemAdmin

default_fieldsets = (
    (None, {
        'fields': ('view', 'view_item')
    }),
    (_('Content'), {
        'fields': ('custom_title', 'content')
    }),
    (_('SEO'), {
        'fields': ('meta_keywords', 'meta_description')
    }),
)
default_visual_editor = ('content',)

def register_admin(cp_item_model, custom_fieldsets=None, visual_editor=default_visual_editor):
    class ContentpagesMenuItemInline(admin.StackedInline):
        model = cp_item_model
        #form = create_advanced_admin_form(ContentpagesMenuItem, ('content',))
        form = create_advanced_admin_form(cp_item_model, _form, visual_editor=visual_editor)
        max_num = 1
        fieldsets = custom_fieldsets or default_fieldsets

    class ContentpagesMenuItemAdmin(MenuItemAdmin):
        save_on_top = True
        inlines = (ContentpagesMenuItemInline,)

    class ContentpagesMenuAdmin(MenuAdmin):
        menu_item_admin_class = ContentpagesMenuItemAdmin

    admin.site.unregister(Menu)
    admin.site.register(Menu, ContentpagesMenuAdmin)


class _form:
    def _check_view(self, view):
        if view:
            from urls import prefix
            fullview = prefix and '%s.%s' % (prefix, view) or view
            bits = fullview.split('.')
            modname, func = '.'.join(bits[:-1]), bits[-1]
            try:
                mod = __import__(modname, {}, {}, [func])
                if not hasattr(mod, func): raise ImportError('')
            except ImportError:
                raise ValidationError(_('View `%s` does not exists') % fullview)
        return view

    def clean_view(self):
        return self._check_view(self.cleaned_data['view'])

    def clean_view_item(self):
        return self._check_view(self.cleaned_data['view_item'])

